package com.example.library

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import kotlinx.android.synthetic.main.activity_test.*
import java.util.*
import java.util.concurrent.Callable
import java.util.concurrent.Executors
import java.util.concurrent.Future
import kotlin.collections.ArrayList


/**
 * 测试有返回值的多线程
 *
 * @author Jack 2017-12-20 16:31
 */
class TestActivity : AppCompatActivity() {
    private val taskSize = 5

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)
        initView()
    }

    private fun initView() {
        btn_test.setOnClickListener {
            initThreadPool()
        }
    }

    private fun initThreadPool() {
        // 创建一个线程池
        val pool = Executors.newFixedThreadPool(taskSize)
        // 创建有多个返回值的任务
        val taskList = ArrayList<Future<Any>>()
        for(i in 1 .. 10 step 2) {
            val callable = TestCallable("task$i")
            val future = pool.submit(callable)
            taskList.add(future)
        }
        // 关闭线程池
        pool.shutdown()
        for (f in taskList) {
            Log.e("TAG", "${f.get()}")
        }
    }

    inner class TestCallable(taskNum: String?) : Callable<Any> {
        private val mTaskNum = taskNum

        override fun call(): Any {
            System.out.println(">>>${mTaskNum}任务启动")
            val dateTmp1 = Date()
            Thread.sleep(1000)
            val dateTmp2 = Date()
            val time = dateTmp2.time - dateTmp1.time
            System.out.println(">>>${mTaskNum}任务终止")
            return "${mTaskNum}任务返回运行结果,当前任务时间【" + time + "毫秒】"
        }
    }
}